﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web.Mvc;
using UscSunShine.Models;
using PagedList;

using UscSunShine.ViewModels.ExtensionMethod;


namespace UscSunShine.Mvc.Controllers
{

    public class RequestController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        private const int pageSize = 10;

        /// <summary>
        /// 查询与分页
        /// </summary>
        /// <param name="departmentID">办事机构ID</param>
        /// <param name="requestCategory">类别</param>
        /// <param name="titleSearchString">查询字</param>
        /// <param name="acceptNumberSearchString">受理单号</param>
        /// <param name="currentDepartmentID">当前办事机构ID</param>
        /// <param name="currentCategory">当前类别</param>
        /// <param name="currentTitle">当前查询字</param>
        /// <param name="currentNumber">当前受理单号</param>
        /// <param name="page">分页页码</param>
        /// <returns></returns>
        public ActionResult Index(
            int? departmentID,
            RequestCategory? requestCategory,
            string titleSearchString,
            string acceptNumberSearchString,
            int? currentDepartmentID,
            RequestCategory? currentCategory,
            string currentTitle,
            string currentNumber,
            int? page)
        {
            //取允许查看的数据
            var requests = RequestsCanBrowse();
            //根据部门ID筛选
            if (departmentID != null)
            {
                requests = requests.Where(t => t.DepartmentID == departmentID);
                currentDepartmentID = departmentID;
            }
            else if (currentDepartmentID != null)
            {
                requests = requests.Where(t => t.DepartmentID == currentDepartmentID);
                departmentID = currentDepartmentID;
            }
            //根据类别筛选
            if (requestCategory.HasValue)
            {
                requests = requests.Where(t => t.RequestCategory == requestCategory);
                currentCategory = requestCategory;
            }
            else if (currentCategory.HasValue)
            {
                requests = requests.Where(t => t.RequestCategory == currentCategory);
                requestCategory = currentCategory;
            }
            //根据查询关键字筛选
            if (titleSearchString != null)
            {
                page = 1;
            }
            else
            {
                titleSearchString = currentTitle;
            }
            if (acceptNumberSearchString != null)
            {
                page = 1;
            }
            else
            {
                acceptNumberSearchString = currentNumber;
            }
            //保存当前状态
            ViewBag.currentTitle = titleSearchString;
            ViewBag.currentCategory = requestCategory;
            ViewBag.currentDepartmentID = departmentID;
            ViewBag.currentNumber = acceptNumberSearchString;
            ViewBag.departmentID = new SelectList(db.Departments, "ID", "Name", departmentID);

            if (requestCategory.HasValue)
            {
                ViewBag.requestCategory = new SelectList(EnumExtension.GetSelectList(typeof(RequestCategory)), "Value", "Text", requestCategory.Value);
            }
            else
            {
                ViewBag.requestCategory = new SelectList(EnumExtension.GetSelectList(typeof(RequestCategory)), "Value", "Text");
            }
            //根据查询关键字筛选数据
            if (!string.IsNullOrWhiteSpace(titleSearchString))
            {
                requests = requests.Where(t => t.Title.Contains(titleSearchString));
            }
            //根据受理单号查询
            if (!string.IsNullOrWhiteSpace(acceptNumberSearchString))
            {
                requests = db.Requests.Where(t => t.AcceptNumber == acceptNumberSearchString);
            }

            requests = requests.OrderByDescending(t => t.AcceptDate);

            var pageNumber = (page ?? 1);

            return View(requests.ToPagedList(pageNumber, pageSize));
        }


        /// <summary>
        /// 取允许浏览的数据
        /// </summary>
        /// <returns></returns>
        private IQueryable<Request> RequestsCanBrowse()
        {
            //取允许浏览的处理状态
            var status = UscSunShine.Models.Request.StatusCanBrowse;
            //取数据
            //未审核的不显示
            var requests = db.Requests.Include(t => t.Department)
                                      .Where(t => status.Contains(t.ProcessStatus));
            return requests;
        }

        // GET: /Request/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Request request = await db.Requests.Include(t => t.Department)
                                               .SingleAsync(t => t.ID == id);
            if (request == null)
            {
                return HttpNotFound();
            }
            //点击次数累加
            request.ViewTimes += 1;
            await db.SaveChangesAsync();
            return View(request);
        }

        // GET: /Request/Create        
        public ActionResult Create(RequestCategory? category)
        {
            var model = new Request {RequestCategory = category ?? RequestCategory.咨询};
            //如果是空则类别为咨询
            model.CreateAcceptNumber();
            return View(model);
        }

        // POST: /Request/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "ID,RequestCategory,AcceptNumber,Title,Content,Username,ContactPhone,Email,ExpectResolveDate")] Request request)
        {
            if (ModelState.IsValid)
            {
                //部门ID
                var department = await db.Departments.FirstOrDefaultAsync();
                request.DepartmentID = department.ID;
                db.Requests.Add(request);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(request);
        }
   
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
